// 成语碎片乱序工具（TypeScript 版本）：传入成语数组，输出混合碎片数组// 成语碎片乱序工具（TypeScript 版本）：传入成语数组，输出混合碎片数组
// 成语碎片乱序工具（TypeScript 版本）：传入成语数组，输出混合碎片对象数组

export interface FragmentItem {
  word: string
  mergeWord: string[]
}

export const generateMixedFragments = (
  idioms: string[],
  level: 1 | 2 | 3 = 2,
): FragmentItem[] => {
  const fragments: FragmentItem[] = []

  idioms.forEach(idiom => {
    const mode = splitModes[Math.floor(Math.random() * splitModes.length)]
    const frags = mode(idiom)
    frags.forEach((frag, idx) => {
      const others = frags.filter((_, i) => i !== idx)
      fragments.push({ word: frag, mergeWord: others })
    })
  })

  return shuffleByLevel(fragments, level)
}

// 拆分模式类型
const splitModes: ((idiom: string) => string[])[] = [
  idiom => [idiom[0], idiom.slice(1, 3), idiom[3]], // 一二一
  idiom => [idiom[0], idiom[1], idiom.slice(2, 4)], // 一一二
  idiom => [idiom.slice(0, 2), idiom[2], idiom[3]], // 二一一
  idiom => [idiom.slice(0, 2), idiom.slice(2, 4)], // 二二
]

const shuffleByLevel = (fragments: FragmentItem[], level: 1 | 2 | 3): FragmentItem[] => {
  switch (level) {
    case 1:
      return partialShuffle(fragments, 1) // 轻度乱序
    case 2:
      return partialShuffle(fragments, 3) // 中度乱序
    case 3:
    default:
      return fullShuffle(fragments) // 完全乱序
  }
}

const partialShuffle = (arr: FragmentItem[], swaps: number = 2): FragmentItem[] => {
  const result = [...arr]
  const len = arr.length
  for (let i = 0; i < swaps; i++) {
    const idx1 = Math.floor(Math.random() * len)
    let idx2 = Math.floor(Math.random() * len)
    while (idx1 === idx2) idx2 = Math.floor(Math.random() * len)
    ;[result[idx1], result[idx2]] = [result[idx2], result[idx1]]
  }
  return result
}

const fullShuffle = (arr: FragmentItem[]): FragmentItem[] => {
  const result = [...arr]
  for (let i = result.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1))
    ;[result[i], result[j]] = [result[j], result[i]]
  }
  return result
}

// 数组乱序
export const shuffleArray = (array: string[]) => {
  for (let i = array.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1))
    ;[array[i], array[j]] = [array[j], array[i]] // 交换元素
  }
  return array
}
